import Router from 'koa-router';
import serviceContent from '../../service/content/index.js';
import serviceModel from '../../service/model/index.js';
import serviceArticle from '../../service/article/index.js';

import response from '../../response.js';
import _ from 'lodash';
const router = new Router();
function transform(value) {
  if (typeof value === 'string') {
    return value;
  }
  if (typeof value === 'number') {
    return value;
  }
  if (typeof value === 'object') {
    return JSON.stringify(value);
  }
  return '';
}
router.post('/', async (ctx) => {
  try {
    const data = ctx.data || {};
    const { articleName, modelId, ...other } = data;
    const articleResult = await serviceArticle.save([[articleName, modelId]]);
    if (!articleResult) {
      return response.fail({ msg: 'fail' });
    }
    const { id: article_id } = articleResult;
    const contents = [];
    Object.keys(other).forEach((key) => {
      const item = data?.[key];
      contents.push({
        key,
        fieldId: item?.id,
        value: JSON.stringify(item?.value),
      });
    });
    const modelResult = serviceModel.findById(modelId);
    if (!modelResult) {
      ctx.body = response.fail({ msg: `${modelId} not in data` });
      return;
    }
    const saveData = contents.map((item) => {
      return [item?.value, modelId, item?.fieldId, article_id];
    });
    const result = await serviceContent.save(saveData);
    if (!result) {
      ctx.body = response.fail({ msg: 'fail' });
    } else {
      ctx.body = response.success({ msg: 'success' });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: 'fail' });
  }
});
router.put('/', async (ctx) => {
  const { id, articleName, modelId, ...other } = ctx.data || {};
  if (_.isNil(id)) {
    ctx.body = response.fail({ msg: 'id not empty' });
    return;
  }
  const articleResult = await serviceArticle.update(id, {
    name: articleName,
    model_id: modelId,
  });
  if (!articleResult) {
    return response.fail({ msg: 'fail' });
  }
  const delResult = await serviceContent.delByArticleId(id);
  if (!delResult) {
    ctx.body = response.fail({ msg: 'fail' });
    return;
  }
  const contents = [];
  Object.keys(other).forEach((key) => {
    const item = other?.[key];
    contents.push({
      key,
      fieldId: item?.id,
      value: JSON.stringify(item?.value),
    });
  });
  const modelResult = serviceModel.findById(modelId);
  if (!modelResult) {
    ctx.body = response.fail({ msg: `${modelId} not in data` });
    return;
  }
  const saveData = contents.map((item) => {
    return [item?.value, modelId, item?.fieldId, id];
  });
  const result = await serviceContent.save(saveData);
  if (!result) {
    ctx.body = response.fail({ msg: 'fail' });
  } else {
    ctx.body = response.success({ msg: 'success' });
  }
});
router.get('/list', async (ctx) => {
  try {
    const list = await serviceArticle.getList();
    ctx.body = response.success({ data: { list: list } });
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: 'fail' });
  }
});
router.get('/:id', async (ctx) => {
  try {
    const { id } = ctx.params || {};
    if (_.isNil(id)) {
      ctx.body = response.fail({ msg: 'id not empty' });
      return;
    }

    const row = await serviceArticle.getDetails(id);
    if (!row) {
      ctx.body = response.fail({ msg: 'fail' });
    } else {
      let modelId = null;
      let name = null;
      const list = row.map((item) => {
        modelId = item?.modelId;
        name = item?.name;
        return { ...item, value: item?.value && JSON.parse(item?.value) };
      });
      ctx.body = response.success({
        data: {
          id: Number(id),
          articleName: name,
          modelId,
          list,
        },
      });
    }
  } catch (e) {
    console.error(e);
    ctx.body = response.fail({ msg: 'fail' });
  }
});
router.delete('/:id', async (ctx) => {
  const { id } = ctx.params || {};
  if (!id && id !== 0) {
    ctx.body = response.fail({ msg: 'id不能为空' });
    return;
  }
  const has = await serviceArticle.findById(id);

  if (!has?.length) {
    ctx.body = response.fail({ msg: '数据不存在' });
    return;
  }
  const result = await serviceArticle.del(id);
  if (result) {
    ctx.body = response.success({ msg: '删除成功' });
  } else {
    ctx.body = response.fail({ msg: '删除失败' });
  }
});
export default router;
